#!/usr/bin/env python
# -*- coding: utf-8 -*-
# datetime: 2024/5/30 下午8:04
# Author: name
# File: params_replace.py
# ide: PyCharm
# description:
import json
import re
from typing import Union


# def get_random_int(num: int):
#     num = num * 10
#     return num
#
#
# def data_to_json(data):
#     import json
#     return json.dumps(data)


number = 2


# fun

class ParamsReplace:
    def __init__(self, params: Union[any]):
        self.params = ""
        self.source_params = params
        self.params_type = type(params)

    def re_find_str(self):
        print("str原始数据", self.source_params)
        match = re.search(r"\${([^${}]*)}", self.source_params) or re.search(r"\${(.*\(.*\)}*)}", self.source_params)
        if match:
            self.params = match.group(1)
            print("正则匹配的结果",self.params)
            result = eval(f"{self.params}")
            print(type(result))
            try:
                result=json.loads(result)

            except:
                pass
            finally:
                self.source_params = self.source_params.replace("${%s}" % self.params, str(result))
                self.re_find_str()
        else:
            return self.source_params

    def re_find_all(self):
        print(self.params_type)
        if self.params_type == list or self.params_type == dict:
            self.source_params = json.dumps(self.source_params, ensure_ascii=False)
            self.re_find_str()
            self.source_params = json.loads(self.source_params)
            return self.source_params
        else:
            self.re_find_str()
            return self.source_params


if __name__ == '__main__':
    test_case = {
        "suit_name": "测试套件${data_to_json(${dic_data})}",
        "suit_desc": "/${get_random_int(${number})}",
    #     # "suit_desc1": "/${data_to_json(${dic_data})}",
    #
    }
    function_code_list = [
        """def get_random_int(num: int):
    num = num * 10
    return num
        """,
        """def data_to_json(data):
    import json
    return json.dumps(data)
        """,
        """dic_data={'a':'aaa','b':'123'}
        """
    ]
    for item in function_code_list:
        exec(item)
    params_replace = ParamsReplace(test_case)
    params_replace.re_find_all()
    print(params_replace.source_params)
    # import json
    #
    # # 原始的 JSON 字符串
    # original_json_str = '{"suit_name": "测试套件", "suit_desc": "/20"}'
    #
    # import json
    #
    # # 原始的 JSON 字符串
    # original_json_str = '{"suit_name": "测试套件", "suit_desc": "/20"}'
    #
    # # 需要替换的字符串
    # replacement_str = "{'a': 'aaa', 'b': '123'}"
    #
    # # 执行替换
    # result_json_str = original_json_str.replace("套件", replacement_str)
    # print(result_json_str)
